package com.tanhua.admin.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Xiao
 * @version 1.0
 * @description 动态审核监听器
 * @date 2021/11/5
 */
@Component
public class AuditListener {
    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate aliyunGreenTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = "tanhua.audit.queue",
                    durable = "true"
            ),
            exchange = @Exchange(
                    value = "tanhua.audit.exchange",
                    type = ExchangeTypes.TOPIC),
            key = {"audit.movement"})
    )
    public void listenCreate(String movementId) throws Exception {
        try {
            //1、根据动态id查询动态
            Movement movement = movementApi.findById(movementId);
            //对于RocketMQ消息有可能出现重复，解决方法判断 (幂等性)
            Integer state = 0;
            if (ObjectUtil.isEmpty(movement) || !movement.getState().equals(state)) {
                return;
            }
            //分别审核文本内容和图片内容
            Map<String, String> textScan = aliyunGreenTemplate.greenTextScan(movement.getTextContent());
            Map<String, String> imageScan = aliyunGreenTemplate.imageScan(movement.getMedias());
            if (CollUtil.isEmpty(textScan) || CollUtil.isEmpty(imageScan)) {
                throw new BusinessException("网络异常，请稍后重试！");
            }
            String textSuggestion = textScan.get("suggestion");
            String imageSuggestion = imageScan.get("suggestion");
            //判断审核结果
            if ("block".equals(textSuggestion) || "block".equals(textSuggestion)) {
                state = 2;  //驳回
            } else if ("pass".equals(textSuggestion) && "pass".equals(textSuggestion)) {
                state = 1;  //通过
            }
            //调用api更新动态的state字段
            List<ObjectId> list = new ArrayList<>();
            list.add(new ObjectId(movementId));
            movementApi.updateState(list, state);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
